﻿using System;
using System.Threading;
using System.Threading.Tasks;

namespace ClassProxitator
{
	/// <summary>
	/// Description of LockingConnection.
	/// </summary>
	public class LockingConnection: IConnection, IProxyClass
	{
        //TODO: CA1001	Types that own disposable fields should be disposable
        // Implement IDisposable on 'LockingConnection' because it creates members of the following IDisposable types: 'SemaphoreSlim'. If 'LockingConnection' has previously shipped, adding new members that implement IDisposable to this type is considered a breaking change to existing consumers.	ClassProxitator	LockingConnection.cs	10

		public LockingConnection(IConnection delegateTo)
		{
			this.Connection = delegateTo;
		}
        readonly SemaphoreSlim locker = new SemaphoreSlim(1);

		public IConnection Connection {get;set;}
		
		public async Task<object> CallMethod(string name, params object[] parameters)
		{
			await locker.WaitAsync();
            try
            {
                return await this.Connection.CallMethod(name, parameters);
            }
            finally
            {
                locker.Release();
            }
		}
	}
}
